package com.hsd.netty.server;

import com.hsd.netty.server.decoder.MessagePackDecoder;
import com.hsd.netty.server.encoder.MessagePackEncoder;
import com.hsd.netty.server.handler.LoginFilterServerHandler;
import com.hsd.netty.server.handler.RemoteServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author s.he
 * on 2020/6/1
 */
@Service
public class Application  implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private static final Integer port = 8081;

    @Autowired
    private LoginFilterServerHandler loginFilterServerHandler;

    @Autowired
    private MessagePackDecoder messagePackDecoder;

    @Autowired
    private MessagePackEncoder messagePackEncoder;

    @Autowired
    private RemoteServerHandler remoteServerHandler;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        run(port);
    }

    public void run(Integer port) {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(workGroup, bossGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel cp) throws Exception {
                            cp.pipeline()
                                    .addLast(new LengthFieldBasedFrameDecoder(65535, 0, 2 ,0, 2))
                                    .addLast(messagePackDecoder)
                                    .addLast(new LengthFieldPrepender(2))
                                    .addLast(messagePackEncoder)
                                    .addLast(new ReadTimeoutHandler(70))
                                    .addLast(loginFilterServerHandler)
                                    .addLast(remoteServerHandler);
                        }
                    });
            logger.info("START NETTY SERVER, LISTEN TO PORT : " + port);
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
